package com.aeric.qrpro;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.aeric.CWDomain.GlobalVariables;
import com.aeric.CWNetwork.BaseActivity;
import com.aeric.CWUtility.DateAndTimeFormatorUtility;

import com.aeric.CWUtility.ToastUtil;
import com.aeric.domain.UserInfo;
import com.aeric.qrpro.custom.CustomScanActivity;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.okhttplib.HttpInfo;
import com.okhttplib.OkHttpUtil;
import com.okhttplib.annotation.CacheType;
import com.okhttplib.callback.Callback;

import java.io.IOException;
import java.util.Date;

public class AmmeterInfoActivity extends BaseActivity implements View.OnClickListener {
    private TextView tv_user_id, tv_user_name, tv_time;
    private EditText et_other_info;
    private Button btn_submit;
    private ImageView btn_scan;
    private final static int CAMERA_CODE = 1002;

    @Override
    protected int initLayout() {
        return R.layout.activity_ammeter_info;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setupActionBar();
        initView();
        setListener();
        initData();
    }


    /**
     * Set up the {@link android.app.ActionBar}, if the API is available.
     */
    private void setupActionBar() {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            // Show the Up button in the action bar.
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setDisplayShowCustomEnabled(true);
            actionBar.setTitle(R.string.info_scan);
        }
    }

    private void initView() {
        tv_user_id = findViewById(R.id.tv_user_id);
        tv_user_name = findViewById(R.id.tv_user_name);
        tv_time = findViewById(R.id.tv_time);
        et_other_info = findViewById(R.id.et_other_info);
        btn_submit = findViewById(R.id.btn_submit);
        btn_scan = findViewById(R.id.btn_scan);

    }
    private void initData() {
        UserInfo userInfo = (UserInfo)getIntent().getSerializableExtra("UserInfo");
        tv_user_id.setText(userInfo.userId);
        tv_user_name.setText(userInfo.userName);
        Date curDate = new Date(System.currentTimeMillis());
        tv_time.setText(DateAndTimeFormatorUtility.DateTimeToString(curDate, DateAndTimeFormatorUtility.DATEANDTIMECOMM));
        et_other_info.setText(null);
    }

    private void setListener() {
        btn_submit.setOnClickListener(this);
        btn_scan.setOnClickListener(this);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == CAMERA_CODE) {
            if (grantResults != null && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
                qrScan();
            } else {
                // Permission Denied
                Toast.makeText(this, "权限被拒绝了", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 扫一扫
     **/
    private void qrScan() {
        IntentIntegrator intentIntegrator = new IntentIntegrator(this);
        intentIntegrator.setCaptureActivity(CustomScanActivity.class);
        intentIntegrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
        intentIntegrator.setOrientationLocked(false);
        intentIntegrator.initiateScan();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == IntentIntegrator.REQUEST_CODE && data != null) {
            IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
            if (result == null) {
                ToastUtil.toastShortTip(this, "HaveNoResult");
            } else {
                String content = result.getContents();
                et_other_info.setText(content);
                et_other_info.setFocusable(false);
                et_other_info.setEnabled(false);
            }
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (v.getId()) {
            case R.id.btn_submit:
                submitNetTask();
                break;
            case R.id.btn_scan:
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                        != PackageManager.PERMISSION_GRANTED) {
                    //  三个参数 第一个参数是 Context , 第二个参数是用户需要申请的权限字符串数组，第三个参数是请求码 主要用来处理用户选择的返回结果
                    ActivityCompat.requestPermissions(this, new String[]{"Manifest.permission.CAMERA"}, CAMERA_CODE);
                } else {
                    qrScan();
                }
                break;
        }
    }

    private void submitNetTask() {
        String userId = tv_user_id.getText().toString();
        String otherInfo = et_other_info.getText().toString();
        String json = "";
        String url = GlobalVariables.SERVICEURL + "/Qrpro/infoSacn";
        getLoadingDialog().showDialog();
        OkHttpUtil.Builder().setCacheType(CacheType.FORCE_NETWORK).setConnectTimeout(5).build(this)
                .doPostAsync(
                        HttpInfo.Builder()
                                .setUrl(url)
                                .addParamJson(json)
                                .build(),
                        new Callback() {
                            @Override
                            public void onSuccess(HttpInfo info) throws IOException {
                                getLoadingDialog().dismiss();
                                String result = info.getRetDetail();
                                ToastUtil.toastLongTip(AmmeterInfoActivity.this, result);
                                initData();
                            }

                            @Override
                            public void onFailure(HttpInfo info) throws IOException {
                                getLoadingDialog().dismiss();
                                ToastUtil.toastShortTip(AmmeterInfoActivity.this, "亲，网络出现问题，请稍候尝试！");
                            }
                        }
                );
    }
}
